function [experiment_Index]=SaveExperiment(conn,runParams,analyteList)
%%%%%
% function to determine if the current experiment is already in the
% database and if it is, does it have the same data collection parameters

%check if the experiment even exists
sql = ['SELECT Experiment_Index FROM Experiments WHERE Experiment_Name='''  runParams.Experiment_Name ''';'];

ret = exec(conn,sql);
ret = fetch(ret);

fields = {'maxSVMPoints','Keep_Ordered','Calc_Accuracy_Spreads',...
    'Plot_Options','Show_Clusters','Show_Peaks','Default_Plots','Show_60hz_Noise','param_plots_2D','param_plots_3D' , ...
    'Remove_Water','Remove_Common_Peaks','Remove_Anomaly','Check_Simularity','Number_SVM_Iterations','Do_PCA'};

dateV = datevec(date);
D=[num2str(dateV(1)) '-' num2str(dateV(2)) '-' num2str(dateV(3)) ];


if (isstruct(ret.Data)==false)
    %if it does not exist, then create the record
   
    sql='INSERT INTO experiments (Experiment_Name,Experiment_Date,Experiment_Comments';
    sql2=[' VALUES ('''  runParams.Experiment_Name ''',''' D ''','' '''];
    
    for I=1:length(fields)
        field = fields{I};
        sql=[sql ',' field]; 
        sql2=[sql2 ',' num2str( runParams.(field))]; %#ok<*AGROW>
    end
    sql2=([sql2 ')']);
    sql =[sql ')' sql2 ';']
    
    exec(conn,sql);
    
    sql = ['SELECT Experiment_Index FROM Experiments WHERE Experiment_Name='''  runParams.Experiment_Name ''';'];
    ret = exec(conn,sql);
    ret = fetch(ret);
    experiment_Index = ret.Data.Experiment_Index;
    
else
    %if it does exist check if it matches the important parameters
    experiment_Index = ret.Data.Experiment_Index;
    
    sql=['update experiments SET Experiment_Date=''' D ''''];
    for I=1:length(fields)
        field = fields{I};
        sql=[sql ',' field '=' num2str( runParams.(field))];
    end
    sql =[sql ');'] %#ok<*NOPRT>
    
    exec(conn,sql);
end

sql =['delete from experiment_analytes where Experiment_Index=' num2str(experiment_Index) ';'];
exec(conn,sql);



for I=1:length(analyteList)
   sql =['Insert into experiment_analytes (Experiment_Index,Analyte_Index,Role) Values (' ...
       num2str(experiment_Index) ',' num2str(analyteList(I)) ',''N'');'];
   exec(conn,sql);
end


end